﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.OpenApi.Models;

namespace Enuo.Dotnet.Api.Utils
{
  public class AddAuthTokenHeaderParameter : IOperationFilter
  {
    /// <summary>
    /// 
    /// </summary>
    /// <param name="operation"></param>
    /// <param name="context"></param>
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
      if (operation.Parameters == null) operation.Parameters = new List<OpenApiParameter>();
      var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;

      //先判断是否是匿名访问,
      var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
      if (descriptor != null)
      {
        var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
        bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
        //非匿名的方法,链接中添加accesstoken值
        if (!isAnonymous)
        {
          operation.Parameters.Add(new OpenApiParameter()
          {
            Name = "authorization",
            In = ParameterLocation.Header, //"query",//query header body path formData
            //Type = "string",
            Required = true //是否必选
          });
        }
      }
    }

  }
}
